
#include "lprefix.h"

#include <typedef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "lstate.h"

#include "clpack.h"
#include "clmain.h"
#include "libenv.h"

#include "exlib.h"
#include "../sdl/sdllibx.h"


#include <string.h>
#include <stdlib.h>


//全局状态机
static lua_State* globalL = null;




//主运行
int main_run(int argc, char* argv[], cstring exeFile, cstring appPath, cstring workPath, PCL_PACK pack)
{
	Env_Argc = argc;
	Env_Argv = argv;

	globalL = luaL_newstate();
	lua_State* L = globalL;
	L->pack.mainPack = pack;
	L->pack.packCount = 256;
	L->pack.packs = (PCL_PACK*)malloc(sizeof(PCL_PACK) * 256);

	L->pack.packs[1] = pack;

	luaL_openlibs(L);
	luaopen_cl(L);
	luaCL_openexlibs(L);
	luaSDL_openexlibs(L);

	//加载核心库包 core.clp
	//L->pack.packs[0]
	//运行核心库包

	//运行程序
	PCL_PACKITEM item = pack->entry;
	luaL_loadbuffer(L, item->data, item->size, pack->file);
	int result = lua_pcall(L, 0, 0, 0);

	return result;
}


static const luaL_Reg exlibs[] = {
  {LUA_CLLIBNAME, luaopen_crosslua},
  {LUA_ENVLIBNAME, luaopen_env},
  {LUA_PATHLIBNAME, luaopen_path},
  {LUA_APPLIBNAME, luaopen_app},
  {NULL, NULL}
};


//类库加载
void luaCL_openexlibs(lua_State* L) {
	const luaL_Reg* lib;
	for (lib = exlibs; lib->func; lib++) {
		luaL_requiref(L, lib->name, lib->func, 1);
		lua_pop(L, 1);
	}
}